/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.yixiang.co

 */
package co.yixiang.tools.service.impl;

import co.yixiang.dozer.service.IGenerator;
import co.yixiang.exception.BadRequestException;
import co.yixiang.tools.domain.AliossConfig;
import co.yixiang.tools.domain.AliossContent;
import co.yixiang.tools.service.AliOSSService;
import co.yixiang.tools.service.AliossConfigService;
import co.yixiang.tools.service.AliossContentService;
import co.yixiang.tools.service.dto.AliOSSQueryCriteria;
import co.yixiang.tools.utils.AliOSSUtil;
import co.yixiang.tools.utils.QiNiuUtil;
import co.yixiang.utils.FileUtil;
import co.yixiang.utils.SecurityUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hupeng
 * @date 2018-12-31
 */
@Service
//@CacheConfig(cacheNames = "alioss")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AliOSSServiceImpl implements AliOSSService {

    private final AliossConfigService aliossConfigService;

    private final AliossContentService aliossContentService;

    private final IGenerator generator;

    @Value("${qiniu.max-size}")
    private Long maxSize;

    public AliOSSServiceImpl(AliossConfigService aliossConfigService, AliossContentService aliossContentService, IGenerator generator) {
        this.aliossConfigService = aliossConfigService;
        this.aliossContentService = aliossContentService;
        this.generator = generator;
    }

    @Override
//    @Cacheable
    public Object queryAll(AliOSSQueryCriteria criteria, Pageable pageable){
        return aliossContentService.queryAll(criteria,pageable);
    }

    @Override
    public List<AliossContent> queryAll(AliOSSQueryCriteria criteria) {
        return aliossContentService.queryAll(criteria);
    }

    @Override
//    @Cacheable(key = "'1'")
    public AliossConfig find() {
        AliossConfig aliossConfig = aliossConfigService.getById(1L);
        return aliossConfig;
    }

    @Override
//    @CachePut(cacheNames = "aliossConfig", key = "'1'")
    @Transactional(rollbackFor = Exception.class)
    public AliossConfig update(AliossConfig aliossConfig) {
//        String http = "http://", https = "https://";
//        if (!(aliossConfig.getHost().toLowerCase().startsWith(http)||aliossConfig.getHost().toLowerCase().startsWith(https))) {
//            throw new BadRequestException("外链域名必须以http://或者https://开头");
//        }
        aliossConfig.setId(1L);
        aliossConfigService.saveOrUpdate(aliossConfig);
        return aliossConfig;
    }

    @Override
//    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public AliossContent upload(MultipartFile file, AliossConfig aliossConfig) {
        FileUtil.checkSize(maxSize, file.getSize());
        if(aliossConfig.getId() == null){
            throw new BadRequestException("请先添加相应配置，再操作");
        }
        //根据时间戳生成文件名称
        String fillname=System.currentTimeMillis()+"_"+file.getOriginalFilename();
        //调用阿里云存储公共方法，上传文件
        AliOSSUtil.addFile(aliossConfig,"upload/"+fillname,file);
        AliossContent content = aliossContentService.getOne(new LambdaQueryWrapper<AliossContent>().eq(AliossContent::getName,fillname));
        if (content == null) {
            //存入数据库
            AliossContent aliossContent = new AliossContent();
            String[] strArray = fillname.split("\\.");
            int suffixIndex = strArray.length -1;
            aliossContent.setSuffix(strArray[suffixIndex]);
            aliossContent.setBucket( aliossConfig.getBucket());
            aliossContent.setType( aliossConfig.getType());
            aliossContent.setName(fillname);
//            aliossContent.setUserId(SecurityUtils.getUserId());
//            aliossContent.setFileType(fileType);
            aliossContent.setUrl( "https://"+aliossConfig.getBucket()+"."+aliossConfig.getHost()+"/upload/"+fillname);
            aliossContent.setSize(FileUtil.getSize(Integer.parseInt(file.getSize()+"")));
//            aliossContent.setProductId(productId);
            aliossContentService.save( aliossContent);
            return  aliossContent;
        }
        return content;
    }

    @Override
//    @Cacheable
    public AliossContent findByContentId(Long id) {
        AliossContent aliossContent = aliossContentService.getById(id);
        return aliossContent;
    }

    @Override
//    @Cacheable
    public String download(AliossContent content,AliossConfig config){
        String finalUrl;
        String type = "公开";
        if(type.equals(content.getType())){
            finalUrl  = content.getUrl();
        } else {
//            Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
//            // 1小时，可以自定义链接过期时间
//            long expireInSeconds = 3600;
//            finalUrl = auth.privateDownloadUrl(content.getUrl(), expireInSeconds);
            finalUrl="";
        }
        return finalUrl;
    }

    @Override
//    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void delete(AliossContent content, AliossConfig config) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(QiNiuUtil.getRegion(config.getZone()));
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(content.getBucket(), content.getName() + "." + content.getSuffix());
            aliossContentService.removeById(content.getId());
        } catch (QiniuException ex) {
            aliossConfigService.removeById(content.getId());
        }
    }

    @Override
//    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void synchronize(AliossConfig config,Long userId, Integer fileType,Long productId) {
        if(config.getId() == null){
            throw new BadRequestException("请先添加相应配置，再操作");
        }
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(QiNiuUtil.getRegion(config.getZone()));
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        //文件名前缀
        String prefix = "";
        //每次迭代的长度限制，最大1000，推荐值 1000
        int limit = 1000;
        //指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
        String delimiter = "";
        //列举空间文件列表
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(config.getBucket(), prefix, limit, delimiter);
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            AliossContent aliossContent;
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                if(aliossContentService.getOne(new LambdaQueryWrapper<AliossContent>().eq(AliossContent::getName,FileUtil.getFileNameNoEx(item.key)))
                        == null){
                    aliossContent = new AliossContent();
                    aliossContent.setSize(FileUtil.getSize(Integer.parseInt(item.fsize+"")));
                    aliossContent.setSuffix(FileUtil.getExtensionName(item.key));
                    aliossContent.setName(FileUtil.getFileNameNoEx(item.key));
                    aliossContent.setType(config.getType());
                    aliossContent.setBucket(config.getBucket());
                    aliossContent.setUrl(config.getHost()+"/"+item.key);
//                    aliossContent.setUserId(SecurityUtils.getUserId());
//                    aliossContent.setFileType(fileType);
//                    aliossContent.setProductId(productId);
                    aliossContentService.save(aliossContent);
                }
            }
        }
    }

    @Override
//    @CacheEvict(allEntries = true)
    public void deleteAll(Long[] ids, AliossConfig config) {
        for (Long id : ids) {
            delete(findByContentId(id), config);
        }
    }

    @Override
//    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(String type) {
        aliossConfigService.update(type);
    }

    @Override
    public void downloadList(List<AliossContent> queryAll, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AliossContent content : queryAll) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("文件名", content.getName());
            map.put("文件类型", content.getSuffix());
            map.put("空间名称", content.getBucket());
            map.put("文件大小", content.getSize());
            map.put("空间类型", content.getType());
            map.put("创建日期", content.getUpdateTime());
//            map.put("用户id",content.getUserId());
//            map.put("文件类型",content.getFileType());
//            map.put("商品id",content.getProductId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}

